<template>
    <div>
        <el-form :model="formData">
            <el-form-item label="选择模板 " desc="" prop="state"
                          disabled="false">
                <div style="display: flex;">
                    <!--  <el-select v-model="formData.templateClassId">
                          <el-option v-for="item in templateClass"></el-option>
                      </el-select>-->
                    <div style="margin-right: 5px">
                        <classSelectOne
                                placeholder="所属分类"
                                typeInfo="generate_template"
                                v-model="formData.templateClassId"
                                :text.sync="formData.templateClassName"
                                @change="(nodeData)=>changeClassTemplate(nodeData)"
                        ></classSelectOne>
                    </div>
                    
                    <el-select v-model="formData.templateIds" :multiple="true"
                               @change="changeTemplate"
                               style="margin-right: 5px"
                    >
                        <el-option v-for="item in templateOptions"
                                   :value="item.id"
                                   :label="item.name"
                        ></el-option>
                    </el-select>
                    <div>
                        <el-button @click="()=>triggerAddTemplateDialog()"
                                   plain type="primary"
                        >新增模板
                        </el-button>
                    </div>
                </div>
            
            </el-form-item>
            <!--选表格-->
            <!--选模板-->
            <!--文件夹路径-->
            <template v-if="expendType==1||expendType==2">
                <div>
                    <!--                src/views/gCode/tableSelect.vue:32-->
                    <el-form-item label="1v1对应的表" desc="" prop="v1TableName"
                                  disabled="false">
                        <tableSelect
                                v-model="formData.v1TableId"
                                :text.sync="formData.v1TableName"
                                @change="(tableData)=>selectv1vTable(tableData)"
                        ></tableSelect>
                    </el-form-item>
                    <div>
                        <div style="margin-bottom: 10px;">
                            <span>指定确定唯一</span>
                            <el-button size="mini" @click="triggerPreview1v1" style="margin-left:5px">确定生成预览</el-button>
                        </div>
                        <div>
                            <el-table :data="filedList" size="mini" border>
                                <el-table-column v-if="!columnsHidden['filedName']" label="字段" prop="filedName"
                                                 min-width="120px;">
                                    <template slot-scope="scope">
                                        <div> {{scope.row.filedName}}</div>
                                    </template>
                                </el-table-column>
                                <el-table-column v-if="!columnsHidden['filedName']" label="确定唯一值" prop="filedName"
                                                 min-width="120px;">
                                    <template slot-scope="scope">
                                        <selectFields :gTableId="formData.gTableId"
                                                      :text.sync="scope.row.sourceFiledName"
                                        ></selectFields>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                
                </div>
            </template>
            <template v-else-if="expendType==3">
                <!--
                 表格2个
                 中间表填写
                 填写中间表的左右字段对应
                 -->
                <div>
                    <!--                src/views/gCode/tableSelect.vue:32-->
                    <el-form-item label="其他表" desc="" prop="v1TableName"
                                  disabled="false">
                        <tableSelect
                                v-model="formData.v1TableId"
                                :text.sync="formData.v1TableName"
                                @change="(tableData)=>selectv1vTable(tableData)"
                        ></tableSelect>
                    </el-form-item>
                    <el-form-item label="中间表名" desc="" prop="v1TableName"
                                  disabled="false">
                        <el-input v-model="formData.middleTableName"></el-input>
                    </el-form-item>
                    <div>
                        <div style="margin-bottom: 10px;">
                            <span>填写对应关系</span>
                            <el-button @click="triggerPreview1v1"  size="mini"  style="margin-left:5px">开始渲染</el-button>
                        </div>
                        <div>
                            <div>左表对应
                            <div>
                                <el-input  v-model="formData.reflectionLeftFeildName"
                                @change="value=>{
                                formData.reflectionLeftFeildNameUp=firstUp(toCamel(value))
                                formData.reflectionLeftFeildNameCamel=toCamel(value)
                                }"
                                ></el-input>
                            </div>
                            </div>
                            <div>右表对应
                                <el-input  v-model="formData.reflectionRightFeildName"
                                           @change="value=>{
                                formData.reflectionRightFeildNameUp=firstUp(toCamel(value))
                                formData.reflectionRightFeildNameCamel=toCamel(value)
                                }"
                                ></el-input>
                            </div>
                        </div>
                        <div>
                        </div>
                    </div>
                
                </div>
            </template>
            <template v-else>
                <div>
                    <el-form-item label="文件夹路径 " desc="" prop="dicPath"
                                  disabled="false">
                        <el-input size="small" placeholder="" v-model="formData.dicPath" clearable />
                    </el-form-item>
                    <!--包路径-->
                    <el-form-item label="包路径 " desc="" prop="packageStr"
                                  disabled="false">
                        <el-input size="small" placeholder="" v-model="formData.packageStr" clearable />
                    </el-form-item>
                </div>
            </template>
            
            
            <!--预览 + 直接编辑模板 +直接编辑内容 -->
            <div>
                <div style="padding-top: 5px;padding-bottom: 10px;font-weight: 600"> 预览</div>
                <el-tabs v-model="activeName" @tab-click="changeActiveNam">
                    <el-tab-pane
                            :label="item.fileName"
                            :name="item.fileName"
                            v-for="(item,index) in formData.fileList"
                    >
                        <div slot="label">
                            {{item.fileName}} <span> <i class="el-icon-edit"
                                                        @click="()=>triggerEditTemplate(item.templateId,index)"
                        ></i></span>
                        </div>
                        <pre v-text="item.fileContent"></pre>
                    </el-tab-pane>
                </el-tabs>
            </div>
        
        
        </el-form>
    
    
    </div>
</template>
<script>
  import * as classApi from '@/apis/sysclass.api.js';
  import * as templateApi from '@/apis/systemplate.api.js';
  import lodash from 'lodash';
  
  
  function firstUp(str) {
    const capitalized = (str && str.charAt(0).toUpperCase()) + (str && str.slice(1));
    return capitalized;
  }
  
  
  function toCamel(str) {
    return str && str.replace(/([^_])(?:_+([^_]))/g, function ($0, $1, $2) {
      return $1 + $2.toUpperCase();
    });
  }
  
  function getJavaType(str) {
    if (str == 'string') {
      return 'String';
    }
    if (str == 'varchar') {
      return 'String';
    }
    if (str == 'long') {
      return 'long';
    }
    if (str == 'int') {
      return 'int';
    }
    if (str == 'datetime') {
      return 'LocalDateTime';
    }
  }
  
  function getJavaTypeByDicValue(dicValue) {
    if (dicValue == 1) {
      return 'string';
    }
    if (dicValue == 1) {
      return 'string';
    }
    if (dicValue == 2) {
      return 'long';
    }
    if (dicValue == 2) {
      return 'int';
    }
    if (dicValue == 3) {
      return 'long';
    }
    if (dicValue == 4) {
      return 'datetime';
    }
  }
  
  function getJavaTypeDefaultValue(row) {
    console.log('getJavaTypeDefaultValue row.type', row.keySmallName, row.type);
    if (row && row.keySmallName == 'delState') {
      return 1;
    }
    if (row && row.type == 'varchar') {
      return '""';
    }
    if (row && row.type == 'string') {
      return '""';
    }
    if (row && row.type == 'long') {
      return '0L';
    }
    if (row && row.type == 'int') {
      return '0';
    }
    if (row && row.type == 'datetime') {
      return 'LocalDateTime.now()';
    }
  }
  
  
  /**
   * @decs java 类型 表达事
   * @params
   * @return
   */
  function getJavaExpression(row, _self = 'this') {
    if (!row) return '';
    if (row && row.type == 'string') {
      return `StringUtils.isEmpty(${_self}.${row.keySmallName})`;
    }
    if (row && row.type == 'varchar') {
      return `StringUtils.isEmpty(${_self}.${row.keySmallName})`;
    }
    if (row.type == 'long') {
      return `${_self}.${row.keySmallName}<=0`;
    }
    if (row.type == 'int') {
      return `${_self}.${row.keySmallName}<=0`;
    }
    if (row.type == 'datetime') {
      return `null==${_self}.${row.keySmallName}`;
    }
    if (row.type == 'object') {
      return `null==${_self}.${row.keySmallName}`;
    }
  }
  
  function getJavaExpressionForDefaultValue(row, _self = 'this') {
    if (!row) return '';
    if (row.type == 'string') {
      return `StringUtils.isEmpty(${_self}.get${firstUp(row.keySmallName)}())`;
    }
    if (row.type == 'varchar') {
      return `StringUtils.isEmpty(${_self}.get${firstUp(row.keySmallName)}())`;
    }
    if (row.type == 'long') {
      return `${_self}.get${firstUp(row.keySmallName)}()<=0`;
    }
    if (row.type == 'int') {
      return `${_self}.get${firstUp(row.keySmallName)}()<=0`;
    }
    if (row.type == 'datetime') {
      return `null==${_self}.get${firstUp(row.keySmallName)}()`;
    }
    if (row.type == 'object') {
      return `null==${_self}.get${firstUp(row.keySmallName)}()`;
    }
  }
  
  
  function getJavaExpressionNotNull(row, _self = 'this') {
    if (!row) return '';
    if (row.type == 'string') {
      return `!StringUtils.isEmpty(${_self}.${row.keySmallName})`;
    }
    if (row.type == 'varchar') {
      return `!StringUtils.isEmpty(${_self}.${row.keySmallName})`;
    }
    if (row.type == 'long') {
      return `${_self}.${row.keySmallName}>0`;
    }
    if (row.type == 'int') {
      return `${_self}.${row.keySmallName}>0`;
    }
    if (row.type == 'datetime') {
      return `null!=${_self}.${row.keySmallName}`;
    }
    if (row.type == 'object') {
      return `null!=${_self}.${row.keySmallName}`;
    }
  }
  
  function getJavaExpressionNotNullforupdate(row, _self = 'this') {
    if (!row) return '';
    if (row.type == 'string') {
      return `!StringUtils.isEmpty(${_self}.get${firstUp(row.keySmallName)}())`;
    }
    if (row.type == 'varchar') {
      return `!StringUtils.isEmpty(${_self}.get${firstUp(row.keySmallName)}())`;
    }
    if (row.type == 'long') {
      return `${_self}.get${firstUp(row.keySmallName)}()>0`;
    }
    if (row.type == 'int') {
      return `${_self}.get${firstUp(row.keySmallName)}()>0`;
    }
    if (row.type == 'datetime') {
      return `null!=${_self}.get${firstUp(row.keySmallName)}()`;
    }
    if (row.type == 'object') {
      return `null!=${_self}.get${firstUp(row.keySmallName)}()`;
    }
  }
  
  
  function adapterCommnet(str) {
    var remptArray = str && str.split && str.split(' ');
    return remptArray && remptArray[0];
  }
  
  
  function isClassId(row) {
    return row && row.keySmallName == 'classId';
  }
  
  function cleardot(str) {
    str = str && str.replaceAll && str.replaceAll('`', '');
    str = str && str.replaceAll && str.replaceAll(`'`, '');
    return str;
  }
  
  function isDic(row) {
    if (!row) return false;
    return (
      row && row.keySmallName.indexOf('state') >= 0 ||
      row && row.keySmallName.toLowerCase().indexOf('type') >= 0 ||
      row && row.comment.indexOf('类型') >= 0
    );
  }
  
  
  import { default as FormDialog } from '@codegenarate/mydialogplus';
  
  import * as  gTableFeildApi from '@/apis/gTableFeild.api.js';
  
  export default {
    data() {
      return {
        activeName: '',
        formData: {
          gTableId: '',
          gTableName: '',
          gTableNameChinese: '',
          templateClassId: '',
          templateClassName: '',
          templateIds: [],
          dicPath: '',
          packageStr: '',
          //{fileName fileContent}
          fileList: [],
          
          v1TableName: '',
          v1TableId: '',
          middleTableName: '',
          //反射
          reflectionLeftFeildName:"",
          reflectionLeftFeildNameUp: '',
          reflectionLeftFeildNameCamel: '',
          
          reflectionRightFeildName: '',
          reflectionRightFeildNameUp:"",
          reflectionRightFeildNameCamel:"",
          /*{v1TableFiledName,sourceFiledName }*/
          uuidList: [],
        },
        filedList: [],
        Rules: {
          dicPath: [{ required: true }],
          packageStr: [{ required: false }],
        },
        columnsHidden: {},
        templateOptions: [],
        fileds: [],
        // 1 1v1
        //2 1v2
        //3 3v3
        expendType: '',
      };
    },
    components: {
      classSelectOne: () => import('@/components/classSelectOne/classSelectOne.vue'),
      selectFields: () => import('@/views/gCode/selectFields.vue'),
      tableSelect: () => import('@/views/gCode/tableSelect.vue'),
    },
    methods: {
      initByDialog(_data) {
        this.formData.gTableId = _data && _data.gTableId;
        this.formData.gTableName = _data && _data.gTableName;
        this.formData.gTableNameChinese = _data && _data.gTableNameChinese;
      },
      async selectv1vTable(tableData) {
        var result = await gTableFeildApi.getList({
          pageNum: 1,
          pageSize: 100,
          gTableId: tableData && tableData.id,
        });
        this.filedList = result && result.data || [];
        console.log('this.filedList===>', this.filedList);
      },
      async changeActiveNam() {
        var index = this.formData.fileList.findIndex(item => item.fileName == this.activeName);
        if (index => 0) {
          var templateId = this.formData.fileList[index].templateId;
          var templateOne = undefined;
          if (templateId) {
            var result = await templateApi.getItem(templateId);
            templateOne = result && result.data;
          }
          this.formData.fileList[index].fileContent = this.renderOne({
            fileds: this.fileds,
            templateContent: templateOne && templateOne.content,
            gTableName: this.formData.gTableName,
          });
        }
      },
      async changeClassTemplate(nodeData) {
        var classIdTemplate = this.formData.templateClassId;
        var result = await templateApi.getList({
          pageNum: 1.,
          pageSize: 100,
          classId: classIdTemplate,
        });
        this.templateOptions = result && result.data || [];
        this.expendType = nodeData && nodeData.expendType;
        
        console.log('expendType', this.expendType);
        
      },
      
      async changeTemplate() {
        var self = this;
        // region  得到模板ids,获取模板列表
        var templateIds = this.formData.templateIds;
        var templateList = [];
        
        for (let i = 0; i < templateIds.length; i++) {
          var templateId = templateIds[i];
          var result = await templateApi.getItem(templateId);
          var one = result && result.data;
          templateList.push({
            keySourceName: this.formData.gTableName,
            fileName: firstUp(toCamel(this.formData.gTableName)) + (firstUp(one && one.name)) + (one && one.fileSuffix),
            templateContent: one && one.content,
            fileContent: '',
            templateId,
          });
          
        }
        // endregion
        
        
        // region   得到表格的字段域
        var result2 = await gTableFeildApi.getList({ gTableId: this.formData.gTableId, pageNum: 1, pageSize: 100 });
        var fileds = result2 && result2.data || [];
        // endregion
        
        
        // region  设置 keySourceName type keySmallName  comment
        for (let i = 0; i < fileds.length; i++) {
          fileds[i].comment = cleardot(fileds[i].filedNameChinese);
          fileds[i].keySourceName = fileds[i].filedName;
          fileds[i].keySmallName = toCamel(fileds[i].keySourceName);
          fileds[i].type = getJavaTypeByDicValue(fileds[i].filedType);
        }
        this.fileds = fileds;
        // endregion
        
        
        // region   字段域+模板列表 生产代码列表
        for (let i = 0; i < templateList.length; i++) {
          templateList[i].fileContent = this.renderOne({
            fileds: fileds,
            templateContent: templateList[i].templateContent,
            gTableName: this.formData.gTableName,
          });
        }
        // endregion
        
        this.formData.fileList = templateList;
      },
      renderOne(data) {
        var self = this;
        var str = '';
        try {
          var uuidList = self.filedList.filter(item => item.sourceFiledName).map(item => {
            if (!item) return undefined;
            return {
              ...item,
              v1TableFiledName: item.v1TableFiledName,
              v1TableFiledNamUp: firstUp(toCamel(item.v1TableFiledName)),
              v1TableFiledNamCamel: (toCamel(item.v1TableFiledName)),
              sourceFiledName: item.sourceFiledName,
              sourceFiledNameUp: firstUp(toCamel(item.sourceFiledName)),
              sourceFiledNameCamel: toCamel(item.sourceFiledName),
              
              
           
            };
          });
          str = lodash.template(data.templateContent)({
            dataList: data.fileds,
            toCamel ,
            tableName: data.gTableName,
            tableNameCamel: toCamel(data.gTableName),
            tableNameUp: this.tableNameUp(data.gTableName),
            firstUpAndCamel: this.tableNameUp,
            firstUp,
            getJavaType,
            getJavaTypeDefaultValue,
            getJavaExpression,
            getJavaExpressionNotNull,
            getJavaExpressionNotNullforupdate,
            getJavaExpressionForDefaultValue,
            adapterCommnet,
            isClassId,
            isDic,
            v1vObject: {
              v1TableName: self.formData.v1TableName,
              v1TableNameUp: self.tableNameUp(self.formData.v1TableName),
              v1TableNameCamel: toCamel(self.formData.v1TableName),
              v1TableId: self.formData.v1TableId,
              uuidList: uuidList,
  
  
              //多对多
              middleTableName:self.formData.middleTableName,
              reflectionLeftFeildName:self.formData.reflectionLeftFeildName,
              reflectionRightFeildName:self.formData.reflectionRightFeildName,
            },
          });
        } catch (e) {
          console.error(e);
        }
        
        return str;
      },
      //第一个字母大写
      tableNameUp(str) {
        return firstUp(toCamel(str));
      },
      async triggerEditTemplate(templateId, index) {
        var self = this;
        var ressultTemplate = await templateApi.getItem(templateId);
        var tempalteOne = ressultTemplate && ressultTemplate.data;
        var result = await FormDialog({
          width: '888px', title: '编辑模板',
          data() {
            return {
              id: templateId,
              ...tempalteOne,
            };
          },
          components: { modify: () => import('@/views/gCode/template/modify.vue') },
        });
        if (!(result && result.success)) {
          return result;
        }
        var ressultTemplate = await templateApi.getItem(templateId);
        var tempalteOne = ressultTemplate && ressultTemplate.data;
        this.templateList[index].fileContent = this.renderOne({
          fileds: this.fileds,
          templateContent: tempalteOne.templateContent,
          gTableName: this.formData.gTableName,
        });
        
        
      },
      async submitByDialog() {
        return { success: true, data: this.formData };
      },
      async triggerAddTemplateDialog() {
        var self = this;
        var result = await FormDialog({
          title: '新增模板',
          width: '666px',
          closeOnClickModal: false,
          data() {
            return {
              classId: self.formData.templateClassId,
              className: self.formData.templateClassName,
            };
          },
          components: {
            modify: () => import('@/views/gCode/template/modify.vue'),
          },
        });
        
        if (result && result.success/*新增成 刷新列*/) {
          this.changeClassTemplate();
        }
      },
   
      
      async triggerPreview1v1() {
        var self = this;
        // region  得到模板ids,获取模板列表
        var templateIds = this.formData.templateIds;
        var templateList = [];
        
        for (let i = 0; i < templateIds.length; i++) {
          var templateId = templateIds[i];
          var result = await templateApi.getItem(templateId);
          var one = result && result.data;
          templateList.push({
            keySourceName: this.formData.gTableName,
            fileName: firstUp(toCamel(this.formData.gTableName)) + (firstUp(one && one.name)) + (one && one.fileSuffix),
            templateContent: one && one.content,
            fileContent: '',
            templateId,
          });
          
        }
        // endregion
        
        
        // region   得到表格的字段域
        var result2 = await gTableFeildApi.getList({ gTableId: this.formData.gTableId, pageNum: 1, pageSize: 100 });
        var fileds = result2 && result2.data || [];
        // endregion
        
        
        // region  设置 keySourceName type keySmallName  comment
        for (let i = 0; i < fileds.length; i++) {
          fileds[i].comment = cleardot(fileds[i].filedNameChinese);
          fileds[i].keySourceName = fileds[i].filedName;
          fileds[i].keySmallName = toCamel(fileds[i].keySourceName);
          fileds[i].type = getJavaTypeByDicValue(fileds[i].filedType);
        }
        this.fileds = fileds;
        // endregion
        
        
        // region   字段域+模板列表 生产代码列表
        for (let i = 0; i < templateList.length; i++) {
          templateList[i].fileContent = this.renderOne({
            fileds: fileds,
            templateContent: templateList[i].templateContent,
            gTableName: this.formData.gTableName,
          });
        }
        // endregion
        
        this.formData.fileList = templateList;
      },
      
    },
  };
</script>
